package com.microservice.user.service.impl;

import com.microservice.api.auth.dto.LoginResponse;
import com.microservice.user.entity.Menu;
import com.microservice.user.mapper.MenuMapper;
import com.microservice.user.service.MenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class MenuServiceImpl implements MenuService {
    
    @Autowired
    private MenuMapper menuMapper;
    
    @Override
    public List<LoginResponse.MenuVO> getUserMenuTree(Long userId) {
        List<Menu> allMenus = menuMapper.selectMenusByUserId(userId);
        List<Menu> menuList = allMenus.stream()
            .filter(m -> "menu".equals(m.getMenuType()))
            .collect(Collectors.toList());
        return buildMenuTree(menuList);
    }
    
    private List<LoginResponse.MenuVO> buildMenuTree(List<Menu> allMenus) {
        List<LoginResponse.MenuVO> rootMenus = new ArrayList<>();
        for (Menu menu : allMenus) {
            if (menu.getParentId() == 0) {
                LoginResponse.MenuVO menuVO = convertToMenuVO(menu);
                menuVO.setChildren(findChildren(menu.getId(), allMenus));
                rootMenus.add(menuVO);
            }
        }
        rootMenus.sort(Comparator.comparing(LoginResponse.MenuVO::getSortOrder));
        return rootMenus;
    }
    
    private List<LoginResponse.MenuVO> findChildren(Long parentId, List<Menu> allMenus) {
        List<LoginResponse.MenuVO> children = new ArrayList<>();
        for (Menu menu : allMenus) {
            if (parentId.equals(menu.getParentId())) {
                LoginResponse.MenuVO menuVO = convertToMenuVO(menu);
                menuVO.setChildren(findChildren(menu.getId(), allMenus));
                children.add(menuVO);
            }
        }
        children.sort(Comparator.comparing(LoginResponse.MenuVO::getSortOrder));
        return children;
    }
    
    private LoginResponse.MenuVO convertToMenuVO(Menu menu) {
        LoginResponse.MenuVO vo = new LoginResponse.MenuVO();
        vo.setId(menu.getId());
        vo.setMenuName(menu.getMenuName());
        vo.setMenuCode(menu.getMenuCode());
        vo.setParentId(menu.getParentId());
        vo.setMenuType(menu.getMenuType());
        vo.setPath(menu.getPath());
        vo.setComponent(menu.getComponent());
        vo.setIcon(menu.getIcon());
        vo.setSortOrder(menu.getSortOrder());
        vo.setPermissionCode(menu.getPermissionCode());
        vo.setChildren(new ArrayList<>());
        return vo;
    }
}
